package com.example.ziliao.ui.no_last_year

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.ziliao.databinding.FragmentNoLastYearBinding
import com.example.ziliao.utils.NumberGenerator
import com.example.ziliao.utils.ViewHelper
import kotlin.random.Random

class NoLastYearFragment : Fragment() {
    private var _binding: FragmentNoLastYearBinding? = null
    private val binding get() = _binding!!

    private lateinit var buttonStart: Button
    private lateinit var optionsContainer: View
    private lateinit var resultText: TextView
    private lateinit var value1: TextView
    private lateinit var value2: TextView
    private lateinit var growth1: TextView
    private lateinit var growth2: TextView
    private lateinit var btnOptionA: Button
    private lateinit var btnOptionB: Button
    private lateinit var btnOptionC: Button
    private lateinit var btnOptionD: Button

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentNoLastYearBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        buttonStart = binding.buttonStart
        optionsContainer = binding.optionsContainer
        resultText = binding.resultText
        value1 = binding.value1
        value2 = binding.value2
        growth1 = binding.growth1
        growth2 = binding.growth2
        btnOptionA = binding.optionA
        btnOptionB = binding.optionB
        btnOptionC = binding.optionC
        btnOptionD = binding.optionD

        buttonStart.setOnClickListener {
            resetOptions()
            generateNumbers()
        }
    }

    private fun generateNumbers() {
        // 使用NumberGenerator生成数字
        val numbers = NumberGenerator.generateControlledNumbers(2)
        val number1 = numbers[0]
        val number2 = numbers[1]
        
        // 生成增长率
        val growth1Value = generateGrowthRate()
        val growth2Value = generateGrowthRate()

        // 显示数值
        value1.text = NumberGenerator.formatDisplayText(listOf(number1))
        value2.text = NumberGenerator.formatDisplayText(listOf(number2))
        growth1.text = String.format("%.1f%%", growth1Value)
        growth2.text = String.format("%.1f%%", growth2Value)

        // 计算正确答案
        val correctAnswer = calculateCorrectAnswer(number1, number2, growth1Value, growth2Value)

        // 生成选项
        generateOptions(correctAnswer)

        // 显示所有组件
        binding.tableLayout.visibility = View.VISIBLE
        binding.questionText.visibility = View.VISIBLE
        binding.optionsContainer.visibility = View.VISIBLE
    }

    private fun generateGrowthRate(): Double {
        var rate: Double
        do {
            rate = Random.nextDouble(-20.0, 20.0)
        } while (rate == 0.0)
        return rate
    }

    private fun calculateCorrectAnswer(number1: Double, number2: Double, growth1Value: Double, growth2Value: Double): Double {
        return (number1 * (1 + growth2Value / 100) / number2 - 1) * 100
    }

    private fun generateOptions(correctAnswer: Double) {
        val options = mutableListOf<Double>()

        // 根据正确答案的绝对值选择迷惑项
        val absAnswer = kotlin.math.abs(correctAnswer)
        val multipliers = when {
            absAnswer <= 1.5 -> listOf(10.0, 5.0, 20.0)
            absAnswer >= 15.0 && absAnswer < 30.0 -> listOf(0.1, 0.5, 0.25)
            else -> listOf(2.0, 3.0, 0.5, 0.333)
        }
        val wrongOption = absAnswer * multipliers.random()

        // 添加选项
        options.add(correctAnswer)  // 正确答案
        options.add(wrongOption)    // 正的迷惑选项
        options.add(-correctAnswer) // 正确答案的负值
        options.add(-wrongOption)   // 负的迷惑选项

        // 随机打乱选项顺序
        val shuffledOptions = options.shuffled()
        val correctIndex = shuffledOptions.indexOf(correctAnswer)

        // 设置选项文本
        btnOptionA.text = "A.${formatOptionText(shuffledOptions[0])}"
        btnOptionB.text = "B.${formatOptionText(shuffledOptions[1])}"
        btnOptionC.text = "C.${formatOptionText(shuffledOptions[2])}"
        btnOptionD.text = "D.${formatOptionText(shuffledOptions[3])}"

        // 设置点击事件
        btnOptionA.setOnClickListener { handleOptionClick(0, correctIndex) }
        btnOptionB.setOnClickListener { handleOptionClick(1, correctIndex) }
        btnOptionC.setOnClickListener { handleOptionClick(2, correctIndex) }
        btnOptionD.setOnClickListener { handleOptionClick(3, correctIndex) }
    }

    private fun formatOptionText(value: Double): String {
        val absValue = kotlin.math.abs(value)
        return if (value >= 0) {
            "上升了${String.format("%.1f%%", absValue)}"
        } else {
            "下降了${String.format("%.1f%%", absValue)}"
        }
    }

    private fun handleOptionClick(selectedIndex: Int, correctAnswer: Int) {
        // 使用ViewHelper处理点击事件
        ViewHelper.handleOptionClick(
            selectedIndex,
            correctAnswer,
            btnOptionA,
            btnOptionB,
            btnOptionC,
            btnOptionD
        )

        // 显示结果
        val value1Num = value1.text.toString().toDouble()
        val value2Num = value2.text.toString().toDouble()
        val growth1Num = growth1.text.toString().replace("%", "").toDouble()
        val growth2Num = growth2.text.toString().replace("%", "").toDouble()
        val correctAnswer = calculateCorrectAnswer(value1Num, value2Num, growth1Num, growth2Num)
        ViewHelper.showResultText(resultText, "准确结果", correctAnswer)
    }

    private fun resetOptions() {
        // 隐藏所有组件
        binding.tableLayout.visibility = View.GONE
        binding.questionText.visibility = View.GONE
        binding.optionsContainer.visibility = View.GONE
        
        // 重置按钮状态
        ViewHelper.resetButtonState(btnOptionA, btnOptionB, btnOptionC, btnOptionD)
        
        // 重置结果文本
        ViewHelper.resetResultText(resultText)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 